package com.bba.manager.user.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.bba.manager.common.util.ResponseEnum;
import com.bba.manager.user.mapper.EmployeeMapper;
import com.bba.manager.common.model.user.Employee;
import com.bba.manager.common.model.user.VO.loginVO;
import com.bba.manager.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录方法
     * @param loginVO 登录视图对象，包含用户名和密码信息
     * @return Employee 返回登录成功的员工对象
     * @throws RuntimeException 当用户不存在或密码错误时抛出异常
     */
    @Override
    public Employee login(loginVO loginVO) {
        if(loginVO.getUsername().isEmpty()||loginVO.getPassword().isEmpty()){
            throw new RuntimeException(ResponseEnum.PLEASE_INPUT_USERNAME.getMessage());
        }
        // 创建Lambda查询构造器，用于数据库查询操作
        LambdaQueryChainWrapper<Employee> query = new LambdaQueryChainWrapper<>(employeeMapper);
        // 根据用户名查询员工信息
        Employee one = query.eq(Employee::getPhone, loginVO.getUsername()).one();
        // 判断用户是否存在，不存在则抛出异常
        if (one == null) {
            throw new RuntimeException(ResponseEnum.USER_ACCOUNT_FORBIDDEN.getMessage());
        }
        // 校验密码是否正确，不正确则抛出异常
        if (!BCrypt.checkpw(loginVO.getPassword(),one.getPassword())) {
            throw new RuntimeException(ResponseEnum.USER_PASSWORD_ERROR.getMessage());
        }

        // 登录成功，返回员工对象
        return one;
    }
}
